package netexpwithoutui.Client;

import domains.Users;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* @author win_d
*
 */
public class Client {

    private Users user;
    private Socket socket;
    private InputStream in;
    private OutputStream out;
    private List friends = null;
    private String ServerIp = "172.0.0.1";
    private int ServerPort = 8090;
    private int port;
    private DatagramSocket datagram;

    public Client(String loginName, String pwd) {
        try {
            this.socket = new Socket(this.ServerIp, this.ServerPort);
        } catch (UnknownHostException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.user = new Users();
        user.setLoginName(loginName);
        user.setPwd(pwd);
        user.setStatus('y');
        //user.setIp();
        try {
            this.datagram = new DatagramSocket();
            this.port = datagram.getPort();
        } catch (SocketException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            this.in = this.socket.getInputStream();
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) throws IOException {
        Client client = new Client("aaa", "bbb");
        boolean login = client.Login();
        System.out.println("login:" + login);
        if (login) {
            ClientAliveReport aliveThread = new ClientAliveReport(client.datagram);
        }
    }

    public boolean Login() throws UnknownHostException, IOException {
        this.socket = new Socket(this.ServerIp, this.ServerPort);
        user.setIp(socket.getLocalAddress().getHostAddress());
        user.setPort(socket.getLocalPort());
        BufferedWriter output = null;
        ObjectInputStream input = null;
        try {
            if (this.socket == null || this.socket.isClosed()) {
                return false;
            }
            String ClientInfo = null;
            ClientInfo = "${login}y" + "${name}" + this.user.getLoginName() + "${pwd}"
                    + this.user.getPwd() + "${port}" + this.port + "${end}";
            output = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));
            output.write(ClientInfo);//½«µÇÂ½ÐÅÏ¢·â×°
            output.flush();
            input = new ObjectInputStream(this.socket.getInputStream());
            try {
                this.friends = (List) input.readObject();
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }

            if (this.friends != null) {
                if (!(Boolean) this.friends.get(0)) {
                    System.out.println((String) this.friends.get(1));
                    return false;
                } else {
                    System.out.println("last Ip:" + (String) this.friends.get(1));
                    this.friends.remove(0);
                    this.friends.remove(0);
                }
            } else {
                return false;
            }
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public void StartChat(Users user) throws IOException {
        if (user.getStatus().equals('y')) {
            ClientThread chatThread = null;
            chatThread = new ClientThread(user);
            chatThread.start();
        }
    }

    public void MessageListener() {//ÏûÏ¢¼àÌý£¬ÊÕµ½ÏûÏ¢¾Í´ò¿ªÏàÓ¦ÁÄÌì´°¿Ú
        while (this.socket.isConnected()) {
            BufferedReader input = null;
            input = new BufferedReader(new InputStreamReader(in));
            try {
                String messageInfo = input.readLine();
                if (messageInfo != null) {
                    int loc1;
                    int loc2;
                    loc1 = messageInfo.indexOf("${name}");
                    loc2 = messageInfo.indexOf("${pwd}");
                    String loginName = messageInfo.substring(loc1 + 6, loc2);
                    for (int i = 0; i < friends.size(); i++) {
                        Users tempUser = (Users) friends.get(i);
                        if (loginName.equals(tempUser.getLoginName())) {
                            ClientThread chatThread = new ClientThread(tempUser);
                            chatThread.start();
                            break;
                        }
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public boolean Logoff() throws IOException {
        if (this.socket.isClosed()) {
            return false;
        } else {
            this.socket.close();
            return true;
        }
    }
}
